import Vue from "vue";
import Router from "vue-router";
import NProgress from 'nprogress';
// 使用router
Vue.use(Router);

const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    { path: "/", redirect: "/mainCenter/welcome" },
    { path: "/login", name: "login", component: ()=> import('@/views/login/login.vue')},
    { 
      path: "/mainCenter", 
      name: "mainCenter",
      component: () => import('@/views/mainCenter/mainCenter.vue'),
      // 一级路由
      children:[
        {
          path:'welcome',
          name:"welcome",
          component: ()=> import('@/layout/welcome.vue')
        },
        {
          path:'shopManagement',
          name:"shopManagement",
          component: ()=> import('@/views/shopManagement/shopManagement.vue'),
          // 商品管理处二级路由
          children:[
            {
              path:'addShop',
              name:"addShop",
              component: ()=> import('@/views/shopManagement/components/addShop.vue')
            },
            {
              path:'onOffShop',
              name:"onOffShop",
              component: ()=> import('@/views/shopManagement/components/onOffShop.vue')
            },
            {
              path:'shopClassified',
              name:"shopClassified",
              component: ()=> import('@/views/shopManagement/components/shopClassified.vue')
            }
          ]
        }
      ]
     },
     {
      path: '/error404',
      name:'error404',
      component:()=>import("@/views/404")
    },
    {
      path: '*',
      name: '404',
      redirect: '/error404'
    }
  ]
});

router.beforeEach(async (to, from, next) => {
  if (to.path === "/login") return next();
  const tokenStr = window.sessionStorage.getItem("token");
  if (!tokenStr) return next("/login");
  next();
});


router.beforeEach((to, from, next) => {
  NProgress.start();
  next();
})

router.afterEach(() => {
  NProgress.done();
})

export default router;